package com.demoworld.daos;

import org.hibernate.Session;
import org.hibernate.Transaction;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


/**
 * Created by francis on 2017/8/26.
 */
public abstract class AbstractBaseDao<T> implements IBaseDao<T> {
    private Class<T> entityClass;
    private Session session;

    public T add(T t) {
        session = HibernateSessionFactory.currentSession();
        Transaction tx = session.beginTransaction();
        try{
            Serializable tmp = session.save(t);
            tx.commit();
        }catch (Exception ex){
            tx.rollback();
        }
        return t;
    }

    public void update(T t) {
        session = HibernateSessionFactory.currentSession();
        Transaction tx = session.beginTransaction();
        try{
            session.update(t);
            tx.commit();
        }catch (Exception ex){
            tx.rollback();
        }
    }

    public void delete(String id) {
        HibernateSessionFactory.currentSession().delete(this.getById(id));
    }

    public T getById(String id) {
        return (T) HibernateSessionFactory.currentSession().get(entityClass, id);
    }

    public AbstractBaseDao() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    @Override
    public void close() {
        if (this.session == null) {
            return;
        }
        this.session.close();
    }
}
